import json
import ssl
import threading
import time
from concurrent.futures import ThreadPoolExecutor

import websockets
from websocket import create_connection

from sql.sql_conn import Mysql_data
from sql.sql_state import insert_data, select_gun
import asyncio
url = 'wss://as-swarm-hongtubet.bcapps.net/'
hast = {'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh,zh-CN;q=0.9',
        'Cache-Control': 'no-cache',
        'Connection': 'Upgrade',
        'Host': 'as-swarm-hongtubet.bcapps.net',
        'Origin': 'https://sb-hk.bc.bangbanged.com',
        'Pragma': 'no-cache',
        'Sec-Websocket-Extensions': 'permessage-deflate; client_max_window_bits',
        'Sec-Websocket-Key': 'ywC6+OGS3zc6etTWzwpntQ==',
        'Sec-Websocket-Version': '13',
        'Upgrade': 'websocket',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36', }
data_1 = {
    "command": "request_session",
    "params": {
        "language": "zhh",
        "site_id": "833",
        "release_date": "20/03/2023-22:17"
    },
    "rid": int(round(time.time(), 4) * 10000)
}
# data_2 = {
#     "command": "get",
#     "params": {
#         "source": "betting",
#         "what": {
#             "competition": [
#                 "name"
#             ],
#             "game": [
#                 "is_blocked",
#                 "info",
#                 "team1_name",
#                 "team2_name",
#             ],
#             "market": [
#                 "name"
#             ],
#             "event": [
#                 "type_1",
#                 "name",
#                 "price"
#                 "base"
#             ]
#         },
#         "where": {
#             "game": {
#                 "id": 22694271
#             },
#             "competition": {
#                 "id": 573
#             },
#             "region": {
#                 "id": 10001
#             },
#             "sport": {
#                 "id": 1
#             }
#         },
#         "subscribe": 'true'
#     },
#     "rid": int(round(time.time(), 5) * 100000)
# }
class Bc(Mysql_data):
    def __init__(self, time_get, time_time):
        self.time_get = time_get
        self.time_time = time_time

    def ddd(self):
        ws = create_connection(url)
        # ws = websockets.connect(url)
        print("websocket 连接成功")
        ws.send(json.dumps(data_1))
        ws.recv()
        return ws


    async def con(self,game_id):
        print("准备连接！")
        while True:
            try:
                async with websockets.connect(url) as websocket:
                    print("websocket 连接成功")
                    try:
                        await websocket.send(json.dumps(data_1))
                        await websocket.recv()
                        nn = 0
                        aa = []
                        for id in game_id:
                            aa.append(self.bb_handle(id,websocket))
                            nn += 1
                        await asyncio.wait(aa)
                        # self.bb_handle(game_id,websocket)
                        # time.sleep(1)
                    except websockets.exceptions.ConnectionClosedError as e:
                        print("connection closed error")
                        print("连接被异常关闭，3秒后开始重连")
                        # time.sleep(3)
                        break
                    except Exception as e:
                        print(e)
            except Exception as e:
                print(e)
                print("重连失败！")




    def conn_1(self):
        mm = 0
        while True:
            try:
                ws = create_connection(url=url, timeout=2, headers=hast, sslopt={"cert_reqs": ssl.CERT_NONE})
                ws.send(json.dumps(data_1))
                ws.recv()
                return ws
            except Exception as e:
                mm += 1
                print('BB连接异常：', e)
                print("BB正在重新连接...")
                if mm == 5:
                    print("退出重新连接")
                    return None
                continue

    def bb_handle(self, game_id, ws):  # ):,ret, region_id, competition_id
        data_2 = self.bisai_data_1(game_id[0], game_id[1], game_id[2])
        ws.send(json.dumps(data_2))
        ret = ws.recv()
        res_data = json.loads(ret.encode().decode("utf8"))  # 'unicode-escape'
        # print(res_data)
        try:
            competition = res_data["data"]["data"]["competition"]
        except Exception as e:
            print("bb_handle:bb_data", e, res_data)
            return None

        data_list_quan_daxiao = []
        data_list_ban_daxiao = []
        data_list_quan_ran = []
        data_list_ban_ran = []
        # print("BB已连接")
        for competition_key in competition:
            league_name = competition[competition_key]["name"]  # 联赛名称
            game = competition[competition_key]["game"]

            for game_key in game:
                game_data = game[game_key]
                is_blocked = game_data["is_blocked"]
                if is_blocked == 0:
                    # print(is_blocked)
                    team1_name = game_data["team1_name"]  # 队伍名称
                    team2_name = game_data["team2_name"]  # 队伍名称
                    info_score = game_data["info"]["score1"] + ":" + game_data["info"]["score2"]  # 得分
                    score = float(game_data["info"]["score1"]) - float(game_data["info"]["score2"])
                    try:
                        current_game_time = game_data["info"]["current_game_time"]  # 比赛进行时间
                    except Exception as e:
                        current_game_time = 0
                    market = game_data["market"]
                    if market == {}:
                        return None
                    for market_key in market:
                        market_name = self.bb_name_ming(market[market_key]["name"])  # 类别    全场大小'全场让分
                        market_name_1 = market[market_key]["name"]

                        event = market[market_key]["event"]
                        event_list = []

                        if "越位" not in market_name_1 and "球员" not in market_name_1 and "方式" not in market_name_1 and "首个" not in market_name_1 and "点球" not in market_name_1 and "客" not in market_name_1 and "剩余" not in market_name_1 and "晋级" not in market_name_1 and "透过" not in market_name_1 and "分钟" not in market_name_1 and "单" not in market_name_1 and "退款" not in market_name_1 and "进" not in market_name_1 and "最高" not in market_name_1 and "/" not in market_name_1 and "个" not in market_name_1 and "三" not in market_name_1 and "项" not in market_name_1 and "胜" not in market_name_1 and "胆" not in market_name_1 and "区间" not in market_name_1 and "精确值" not in market_name_1 and "或" not in market_name_1 and "哪一队" not in market_name_1:
                            # print(market_name,"-------------",market_name_1,"++++++++++++")
                            for event_key in event:
                                event_price = round(float(event[event_key]["price"]), 2)  # 倍率 类别名称得分
                                event_name = event[event_key]['name'].strip()  # 类别名称 大  小
                                if market_name != None and (
                                        "大" in market_name or "让" in market_name or "总得分" in market_name):
                                    try:
                                        event_base = event[event_key]["base"]  # 类别名称得分前面那个数据  1.5/2   2.25
                                    except:
                                        event_base = None
                                    if event[event_key]['type_1'] == "Away":
                                        event_base -= score
                                    if event[event_key]['type_1'] == "Home":
                                        event_base += score
                                    if ".25" in str(event_base) or ".75" in str(event_base):
                                        event_base = self.bb_num(event_base)
                                    if '让' in market_name and event_base != 0 and "-" not in str(event_base):
                                        event_base = "+" + str(event_base)
                                    event_list.append((event_name, event_base, round(event_price - 1, 2)))
                                elif market_name != None and "独赢" in market_name:
                                    event_list.append([event_name, event_price])
                                else:
                                    event_list.append([event_name, round(event_price - 1, 2)])
                            try:
                                if len(event_list[0]) > 2:
                                    data_all = self.time_get, league_name, current_game_time, info_score, team1_name, team2_name, market_name, \
                                        event_list[0][0], event_list[0][1], event_list[0][2], event_list[1][0], \
                                        event_list[1][1], \
                                        event_list[1][2], self.time_time
                                    # print(data_all)
                                    # print(market_name_1,"--------------------",market_name)

                                    if "全" in market_name:
                                        if "让" in market_name:
                                            data_list_quan_ran.append(data_all)
                                        else:
                                            data_list_quan_daxiao.append(data_all)
                                            if ("小" in data_all[7] and float(data_all[9]) >= 0.3 and int(
                                                    data_all[2]) >= 89) or (
                                                    "小" in data_all[10] and float(data_all[12]) >= 0.3 and int(
                                                    data_all[2]) >= 89):
                                                pass


                                    else:
                                        if "让" in market_name:
                                            data_list_ban_ran.append(data_all)
                                        else:
                                            data_list_ban_daxiao.append(data_all)

                            except Exception as e:
                                print("bb_handle_game: ", e)
                                pass
        if len(data_list_quan_daxiao) != 0:
            idd = insert_data("bc")
            self.run_sql(idd, data_list_quan_daxiao)
            # print(idd)
        if data_list_ban_daxiao != []:
            idd2 = insert_data("bc_ban")
            self.run_sql(idd2, data_list_ban_daxiao)
            # print(idd2)
        if len(data_list_quan_ran) != 0:
            idf3 = insert_data("bc_ran")
            self.run_sql(idf3, data_list_quan_ran)
            # print(idf3)
        if data_list_ban_ran != []:
            idd4 = insert_data("bc_ban_ran")
            self.run_sql(idd4, data_list_ban_ran)
            # print(idd4)

    def bisai_data_1(self, game_id, region_id, competition_id):
        data_bisai = {
            "command": "get", "params": {
                "source": "betting", "what": {
                    "competition": ["name"],
                    "game": ["info", "team1_name", "team2_name", "is_blocked"],
                    "market": ["name"],
                    "event": ["type_1", "name", "price", "base"]},
                "where": {"game": {"id": game_id}, "competition": {"id": competition_id},
                          "region": {"id": region_id}, "sport": {"id": 1}},
                "subscribe": "true"},
            "rid": int(round(time.time(), 5) * 100000)

        }
        return data_bisai

    def bb_name_ming(self, wanfa_name):

        # print(wanfa_name)
        if "大小" in wanfa_name or "总得分" in wanfa_name:
            if "大小" in wanfa_name and "全场" in wanfa_name:
                if "角球" in wanfa_name:
                    if "主" in wanfa_name:
                        eventbase = "全主角大小"
                    elif "客" in wanfa_name:
                        eventbase = "全客角大小"
                    else:
                        eventbase = "全场角球大小"
                elif "黄牌" in wanfa_name:
                    if "主" in wanfa_name:
                        eventbase = "全主黄牌大小"
                    elif "客" in wanfa_name:
                        eventbase = "全客黄牌大小"
                    else:
                        eventbase = "全场黄牌大小"
                elif "红牌" in wanfa_name:
                    if "主" in wanfa_name:
                        eventbase = "全主红牌大小"
                    elif "客" in wanfa_name:
                        eventbase = "全客红牌大小"
                    else:
                        eventbase = "全场红牌大小"
                else:
                    if "主" in wanfa_name:
                        eventbase = "全场主大小"
                    elif "客" in wanfa_name:
                        eventbase = "全场客大小"
                    else:
                        eventbase = "全场大小"
                return eventbase
            elif ("半场" in wanfa_name and "大小" in wanfa_name) or "总得分" in wanfa_name:
                if "角球" in wanfa_name:
                    if "第1半场" in wanfa_name or "上" in wanfa_name:
                        if "主" in wanfa_name:
                            eventbase = "上半主角大小"
                        elif "客" in wanfa_name:
                            eventbase = "上半客角大小"
                        else:
                            eventbase = "上半角球大小"
                    else:
                        if "主" in wanfa_name:
                            eventbase = "下半主角大小"
                        elif "客" in wanfa_name:
                            eventbase = "下半客角大小"
                        else:
                            eventbase = "下半角球大小"
                elif "黄牌" in wanfa_name:
                    if "第1半场" in wanfa_name or "上" in wanfa_name:
                        if "主" in wanfa_name:
                            eventbase = "上半主黄牌大小"
                        elif "客" in wanfa_name:
                            eventbase = "上半客黄牌大小"
                        else:
                            eventbase = "上半黄牌大小"
                    else:
                        if "主" in wanfa_name:
                            eventbase = "下半主黄牌大小"
                        elif "客" in wanfa_name:
                            eventbase = "下半客黄牌大小"
                        else:
                            eventbase = "下半黄牌大小"
                else:
                    if "第1半场" in wanfa_name or "上" in wanfa_name:
                        if "主" in wanfa_name:
                            eventbase = "上半主大小"
                        elif "客" in wanfa_name:
                            eventbase = "上半客大小"
                        else:
                            eventbase = "上半场大小"
                    else:
                        if "主" in wanfa_name:
                            eventbase = "下半主大小"
                        elif "客" in wanfa_name:
                            eventbase = "下半客大小"
                        else:
                            eventbase = "下半场大小"
                return eventbase


        elif "让分" in wanfa_name or "让球" in wanfa_name:
            if "全场" in wanfa_name:
                if "角" in wanfa_name:
                    if "主" in wanfa_name:
                        eventbase = "全场主角让"
                    elif "客" in wanfa_name:
                        eventbase = "全场客角让"
                    else:
                        eventbase = "全场角球让"
                elif "黄牌" in wanfa_name:
                    if "主" in wanfa_name:
                        eventbase = "全场主黄牌让"
                    elif "客" in wanfa_name:
                        eventbase = "全场客黄牌让"
                    else:
                        eventbase = "全场黄牌让"
                else:
                    if "主" in wanfa_name:
                        eventbase = "全场主让"
                    elif "客" in wanfa_name:
                        eventbase = "全场客让"
                    else:
                        eventbase = "全场让"
                return eventbase
            elif "半场" in wanfa_name:
                if "角" in wanfa_name:
                    if "第1 半场" in wanfa_name or "上" in wanfa_name:
                        if "主" in wanfa_name:
                            eventbase = "上半主角让"
                        elif "客" in wanfa_name:
                            eventbase = "上半客角让"
                        else:
                            eventbase = "上半角球让"
                    else:
                        if "主" in wanfa_name:
                            eventbase = "下半主角让"
                        elif "客" in wanfa_name:
                            eventbase = "下半客角让"
                        else:
                            eventbase = "下半角球让"
                elif "黄牌" in wanfa_name:
                    if "第1 半场" in wanfa_name or "上" in wanfa_name:
                        if "主" in wanfa_name:
                            eventbase = "上半主黄牌让"
                        elif "客" in wanfa_name:
                            eventbase = "上半客黄牌让"
                        else:
                            eventbase = "上半黄牌让"
                    else:
                        if "主" in wanfa_name:
                            eventbase = "下半主黄牌让"
                        elif "客" in wanfa_name:
                            eventbase = "下半客黄牌让"
                        else:
                            eventbase = "下半黄牌让"
                else:
                    if "第1 半场" in wanfa_name or "上" in wanfa_name:
                        if "主" in wanfa_name:
                            eventbase = "上半主让"
                        elif "客" in wanfa_name:
                            eventbase = "上半客让"
                        else:
                            eventbase = "上半场让"
                    else:
                        if "主" in wanfa_name:
                            eventbase = "下半主让"
                        elif "客" in wanfa_name:
                            eventbase = "下半客让"
                        else:
                            eventbase = "下半场让"

                return eventbase

        else:
            return wanfa_name

    def bb_num(self, event_base):
        if "-" not in str(event_base):
            if ".25" in str(event_base):
                eventbase = event_base
                event_base = str(int(eventbase - float(0.25))) + "/" + str(eventbase + float(0.25))
                # print(event_base,eventbase)

            elif ".75" in str(event_base):
                eventbase = event_base
                event_base = str(eventbase - float(0.25)) + "/" + str(int(eventbase + float(0.25)))
                # print(event_base,eventbase)

            return event_base
        else:
            # print(event_base)
            if ".25" in str(event_base):
                eventbase = event_base
                if "0.25" in str(event_base):
                    event_base = "-" + str(int(eventbase + float(0.25))) + "/" + str(-eventbase + float(0.25))
                else:
                    event_base = str(int(eventbase + float(0.25))) + "/" + str(-eventbase + float(0.25))

            elif ".75" in str(event_base):
                eventbase = event_base
                event_base = str(eventbase + float(0.25)) + "/" + str(int(-eventbase + float(0.25)))

            return event_base

    def run_bc(self, get_id):
        nn = 0

        ws = self.conn_1()
        with ThreadPoolExecutor(len(get_id)) as t:
            for id in get_id:
                # asyncio.get_event_loop().run_until_complete(self.con(id))
                t.submit(self.bb_handle, id, ws)
                nn += 1
        print(nn, "BC OK")
        ws.close()
        return



    def bb_fb(self):

        try:
            fb_bb_id = select_gun("FB_game_id,BB_game_id,BB_region_id,BB_competition_id", 'bisai_fb_bb_duiwu')
            id_all = self.run_sql(fb_bb_id)
            if len(id_all) != 0:
                fb_id = [i[0] for i in id_all]
                bb_id = [(i[1], i[2], i[3]) for i in id_all]
                th_bb = threading.Thread(target=self.run_bc, args=[bb_id])
                # th_fb = threading.Thread(target=self.run_fb, args=([fb_id], t1, t2))
                th_bb.start()
                # asyncio.run(self.run_bc(bb_id))
                aa = []
                id_nun = len(fb_id) // 5
                num = len(fb_id) % 5
                if num == 0:
                    pego = id_nun
                else:
                    pego = id_nun + 1
                # for i in range(pego):
                    # th_1 = threading.Thread(target=self.run_fb, args=(fb_id[i * 5:(i + 1) * 5], t1, t2))
                    # th_1.start()
                    # aa.append(th_1)

                # for i in aa:
                #     i.join()
                # fb_th.join()
                th_bb.join()
                print(time.time() - t2)
                # if len(get_id) <= 25:
                time.sleep(1.5)
            else:
                print("等等")
                time.sleep(120)
        except Exception as e:
            print(e)
            time.sleep(20)


if __name__ == '__main__':

    while True:
        t1 = time.strftime("%Y-%m-%d %X", time.localtime())
        t2 = time.time()
        a= Bc(t1,t2+6)
        a.bb_fb()
